import Vue from 'vue';
import router from '@/router';

export default {
  namespaced: true,
  state: {
    // 尺寸
    value: '', // medium small mini
  },
  actions: {
    /**
     * @description 将当前的设置应用到 element
     * @param {Boolean} refresh 是否在设置之后刷新页面
     */
    apply({ state, commit }, refresh) {
      Vue.prototype.$ELEMENT.size = state.value;
      if (refresh) {
        commit('vxadmin/page/keepAliveClean', null, { root: true });
        router.replace('/refresh');
      }
    },
    /**
     * @description 确认已经加载组件尺寸设置 issues/198
     */
    isLoaded({ state }) {
      if (state.value) return Promise.resolve();
      return new Promise((resolve) => {
        const timer = setInterval(() => {
          if (state.value) {
            resolve(clearInterval(timer));
          }
        }, 10);
      });
    },
    /**
     * @description 设置尺寸
     * @param {Object} state vuex state
     * @param {String} size 尺寸
     */
    set({ state, dispatch }, size) {
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async (resolve) => {
        // store 赋值
        state.value = size;
        // 应用
        dispatch('apply');
        // 持久化
        await dispatch(
          'vxadmin/db/set',
          {
            dbName: 'sys',
            path: 'size.value',
            value: state.value,
            user: true,
          },
          { root: true },
        );
        // end
        resolve();
      });
    },
    /**
     * @description 从持久化数据读取尺寸设置
     * @param {Object} state vuex state
     */
    load({ state, dispatch }) {
      // eslint-disable-next-line no-async-promise-executor
      return new Promise(async (resolve) => {
        // store 赋值
        state.value = await dispatch(
          'vxadmin/db/get',
          {
            dbName: 'sys',
            path: 'size.value',
            defaultValue: 'default',
            user: true,
          },
          { root: true },
        );
        // 应用
        dispatch('apply');
        // end
        resolve();
      });
    },
  },
};
